/*
 *
 * Copyright (c) 2020 The Raptor Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#ifndef RAPTOR_LITE_SRC_WINDOWS_IOCP_THREAD_H_
#define RAPTOR_LITE_SRC_WINDOWS_IOCP_THREAD_H_

#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <vector>
#include <unordered_map>

#include "raptor-lite/utils/atomic.h"
#include "raptor-lite/utils/mpscq.h"
#include "raptor-lite/utils/status.h"
#include "raptor-lite/utils/sync.h"
#include "raptor-lite/utils/thread.h"

#include "src/common/common.h"
#include "src/windows/iocp.h"

namespace raptor {
typedef struct {
    OVERLAPPED overlapped;
    int event_type;
    uint32_t user_id;
} OverLappedEx;

struct EventDetail {
    void *ptr;
    int event_type;
    int error_code;
    uint32_t transferred_bytes;
    OverLappedEx *overlaped;
};

struct PollingThreadMessageNode {
    MultiProducerSingleConsumerQueue::Node node;
    EventDetail detail;
};

class PollingThread {
public:
    PollingThread();
    ~PollingThread();
    raptor_error Init(int rs_threads, int kernel_threads = 0);
    raptor_error Start();
    void Shutdown();

    bool Add(SOCKET sock, internal::EventReceivingService *service);
    raptor_error AddThreads(int threads);
    void Delete(SOCKET sock);

private:
    void WorkThread(void *);
    void OnEventProcess(EventDetail *detail);

    bool shutdown_;

    std::vector<Thread *> thds_;

    Iocp iocp_;

    std::unordered_map<SOCKET, internal::EventReceivingService *> fd_table_;

    RWLock lock_;
};

} // namespace raptor

#endif // RAPTOR_LITE_SRC_WINDOWS_IOCP_THREAD_H_
